<template>
 <div style="width:100vw;display:flex;justify-content: center;background:#F9F9F9">
    <div class="container" style="width: 75vw;padding:0px 20px 40px 20px;padding-top: 0px;">
      <ExamNavBar :examId="examId" :semesterId="semesterId" />
      <!-- 成绩概览 -->
        <div class="content-section">
            <div class="section-header" @click="toggleSection('overview')">
              <p class="section-title">成绩概览 
                <i class="arrow" :class="{ 'rotate': isSectionVisible.overview }"></i>
              </p>
            </div>
            <transition name="slide">
              <div class="analysis-section"  v-show="isSectionVisible.overview">
                <table class="score-table">
                  <thead>
                    <tr>
                      <th>考试总分</th>
                      <th>平均分</th>
                      <th>最高分</th>
                      <th>最低分</th>
                      <th>应到人数</th>
                      <th>实到人数</th>
                      <th>优秀人数</th>
                      <th>良好人数</th>
                      <th>及格人数</th>
                      <th>不及格人数</th>
                    </tr>
                  </thead>
                  <tbody v-if="paperData">
                    <tr>
                      <td>{{ paperData.total_score }}</td>
                      <td>{{ paperData.average_score }}</td>
                      <td>{{ paperData.max_score }}</td>
                      <td>{{ paperData.min_score }}</td>
                      <td>{{ paperData.candidate_num }}</td>
                      <td>{{ paperData.exam_num }}</td>
                      <td>{{ paperData.best_counts }}</td>
                      <td>{{ paperData.good_counts }}</td>
                      <td>{{ paperData.pass_counts }}</td>
                      <td>{{ paperData.fail_counts }}</td>
                    </tr>
                  </tbody>
                  <tbody v-else>
                  <tr><td colspan="10" style="text-align: center;">加载中...</td></tr>
                </tbody>
                </table>
              </div>
            </transition>
         </div>
      <!-- 详细分析 -->
      <div class="content-section">
        <div class="section-header" @click="toggleSection('detail')">
          <p class="section-title">
            详细分析
            <i class="arrow" :class="{ 'rotate': isSectionVisible.detail }"></i>
          </p>
        </div>
        <transition name="slide">
          <div class="analysis-section" v-show="isSectionVisible.detail">
            <el-table 
              :data="questionData" 
              border 
              style="width: 100%"
              @expand-change="handleExpand"
              ref="questionTable"
            >
              <!-- 展开列 -->
              <el-table-column type="expand" width="60">
                 <template #header>
                  <span 
                    @click.stop="toggleAllExpansion"
                     style="cursor: pointer;color:#409EFF"
                  >
                    {{ isAllExpanded ? '收起' : '展开' }}
                  </span>
                </template>
                <template #default="{ row }">
                  <div class="detail-card">
                    <div class="detail-left">
                       <p class="sub-title">{{ row.type === '简答题' ? '正确答案' : '选项内容' }}</p>
                        <template v-if="row.type !== '简答题'">
                          <ul>
                            <li 
                              v-for="option in row.options" 
                              :key="option.id"
                              :class="{ 'correct-answer': option.isCorrect }"
                              :style="{ color: option.isCorrect ? '#67C23A' : '' }"
                            >
                              {{ option.label }}. {{ option.text }}
                              <span v-if="option.isCorrect">✓</span>
                            </li>
                          </ul>
                        </template>
                        <div v-else class="correct-answer" style="padding:10px 0;">
                          {{ stripTags(row.correctAnswer) || '-' }}
                        </div>
                    <div class="answer-tip">
                      <span>所属知识点：{{ row.knowledgePoint || '-' }}</span>
                    </div>
                  </div>
                    <div class="detail-right">
                      <p class="sub-title">答题情况</p>
                      <el-table :data="row.answers" border size="small">
                        <el-table-column prop="option" label="选项" width="80" align="center"/>
                        <el-table-column prop="count" label="人数" width="100" align="center"/>
                        <el-table-column label="比例" align="center">
                          <template #default="{ row }">
                            <el-progress :percentage="row.percentage" :stroke-width="12"/>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                  </div>
                </template>
              </el-table-column>

              <!-- 常规列 -->
              <el-table-column type="index" label="题号" width="60" align="center" :index="indexMethod"/>
              <el-table-column prop="content" label="题目内容" min-width="200">
                <template #default="{ row }">
                  {{ stripTags(row.content) }}
                </template>
              </el-table-column>
              <el-table-column prop="type" label="题型" width="100" align="center"/>
              <el-table-column prop="accuracy" label="正确率" width="80" align="center">
                <template #default="{ row }">
                  {{ row.accuracy }}
                </template>
              </el-table-column>
              <el-table-column prop="scoreRate" label="得分率" width="80" align="center">
                <template #default="{ row }">
                  {{ row.scoreRate }}
                </template>
              </el-table-column>
              <el-table-column prop="answered" label="已答" width="80" align="center"/>
              <el-table-column prop="unanswered" label="未答" width="80" align="center"/>
              <el-table-column prop="total" label="总数" width="80" align="center"/>
            </el-table>
          </div>
        </transition>
      </div>


<!-- 分布情况 -->
      <div class="content-section combined-section">
        <div class="section-header" @click="toggleSection('distribution')">
          <p class="section-title">
            分布情况
            <i class="arrow" :class="{ 'rotate': isSectionVisible.distribution }"></i>
          </p>
        </div>
        <transition name="slide">
          <div class="chart-row" v-show="isSectionVisible.distribution">
            <!-- 词云区块 -->
            <div class="chart-container word-cloud" style="background: linear-gradient(360deg, rgb(255, 255, 255), rgba(52, 143, 154, 0.65), rgb(0 80 200));">
              <div class="circle-ripple"></div>
              <p class="sub-title" style="color: white;border-left: 4px solid white;">知识点考察情况</p>
            <div >
            <div ref="wordCloudChart" class="chart"></div></div>
            </div>
            
            <!-- 成绩分布区块 -->
            <div class="chart-container pie-chart">
              <div style="display: flex;
                justify-content: space-between;
                align-items: flex-start;">
                <p class="sub-title">成绩分布情况</p>
                <el-radio-group v-model="chartType" @change="drawChart">
                  <el-radio-button label="pie">饼图</el-radio-button>
                  <el-radio-button label="funnel">漏斗图</el-radio-button>
                </el-radio-group>
              </div>
              <div ref="pieChart" class="chart"></div>
            </div>
          </div>
        </transition>
      </div>
        <!-- 分班对比 折柱混合图 -->
        <div class="content-section" style="padding: 20px 30px 80px 30px;">
            <div class="section-header" @click="toggleSection('comparison')" >
               <p class="section-title">分班对比
                  <i class="arrow" :class="{ 'rotate': isSectionVisible.comparison }"></i>
               </p>
            </div>
          <transition name="slide">
            <div class="analysis-section" v-show="isSectionVisible.comparison">
              <div ref="echart" class="chart" style="margin-top: 120px;height:500px;margin-bottom: 0px"></div>
            </div>
          </transition>
        </div>

    </div>
  </div>
</template>

<script>
import { fetchPaperData, fetchDivisionData, fetchPointData,fetchScoreData, fetchQuestionList,fetchQuestionDetail } from '@/services/api';
import ExamNavBar from '@/components/ExamNavBar.vue';
import * as echarts from 'echarts';
import 'echarts-wordcloud';


export default {
  name: 'AnalysisReport',
  components: { ExamNavBar },
  data() {
    return {
      isAllExpanded: false,
      paperData: null,         // 成绩概览数据
      divisionData: { divisionDatas: [] }, // 分班数据
      selectedDivision: 0,      // 默认选择第一个班级
      questionAverages: [],     // 题目平均分数据
      wordCloudData: [],        // 词云数据
      pieChartData: [],         // 饼状图数据
      questionData: [],
      chartType: 'pie', // 新增图表类型状态
       isSectionVisible: {
        overview: true,    // 成绩概览
        comparison: false,  // 分班对比
        distribution: false,  // 分布状态
        detail: true
      },
  };
  },
  mounted() {
    this.examId = this.$route.params.examId
    this.semesterId = this.$route.params.semesterId
    this.loadData();
  },
  methods: {
     stripTags(html) {
    const tmp = document.createElement("div");
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText || "";
  },
     mapQuestionType(qsType) {
    const typeMap = {
      only_sel: '单选题',
      many_sel: '多选题',
      yesorno: '判断题',
      qna: '简答题'
    };
    return typeMap[qsType] || '未知题型';
  },

  // 解析选项
parseOptions(qsType, detail) {
  if (qsType === 'qna') return [];
  return detail.options?.map((opt, index) => ({
    label: String.fromCharCode(65 + index), // 生成ABCD
    text: this.stripTags(opt.option_content), // 去除HTML标签
    isCorrect: opt.is_right
  })) || [];
},

  // 解析答案
  parseAnswers(qsType, detail) {
    if (qsType === 'qna') {
      return detail.qnaLevels?.map(lvl => ({
        option: lvl.level,
        count: lvl.level_cnt,
        percentage: lvl.level_percent * 100
      })) || [];
    }
    return detail.options?.map((opt, index) => ({
      option: String.fromCharCode(65 + index), // 生成ABCD
      count: opt.choose_cnt,
      percentage: opt.choose_percent * 100
    })) || [];
  },

     indexMethod(index) {
    return index + 1;  // 让序号从1开始
  },
     toggleAllExpansion() {
    this.isAllExpanded = !this.isAllExpanded;
    this.questionData.forEach(row => {
      // 使用可选链操作符防止未定义错误
      this.$refs.questionTable?.toggleRowExpansion(row, this.isAllExpanded);
    });
  },
     handleExpand() {
    this.$nextTick(() => {
      const charts = [this.$refs.echart, this.$refs.wordCloudChart, this.$refs.pieChart];
      charts.forEach(chart => {
        const instance = chart && echarts.getInstanceByDom(chart);
        instance && instance.resize({ silent: true });
      });
    }); 
    },
toggleSection(section) {
  
  this.isSectionVisible[section] = !this.isSectionVisible[section];

  // 使用 Vue 的 $nextTick 确保 DOM 变化后执行 resize
  this.$nextTick(() => {
    if (section === 'comparison' && this.$refs.echart) {
      echarts.getInstanceByDom(this.$refs.echart)?.resize();
    } else if (section === 'distribution') {
      if (this.$refs.wordCloudChart) {
        echarts.getInstanceByDom(this.$refs.wordCloudChart)?.resize();
      }
      if (this.$refs.pieChart) {
        echarts.getInstanceByDom(this.$refs.pieChart)?.resize();
      }
    }
  });
},
      drawChart() {
    if (this.chartType === 'pie') {
      this.drawPieChart();
    } else {
      this.drawFunnelChart();
    }
  },
   async loadData() {
  console.log("Exam ID:", this.examId);
  console.log("Semester ID:", this.semesterId);
  

  try {
    const [paperRes, divisionRes, pointRes,scoreRes, qsListRes] = await Promise.all([
      fetchPaperData(this.examId, this.semesterId),
      fetchDivisionData(this.examId, this.semesterId),
      fetchPointData(this.examId),
      fetchScoreData(this.examId, this.semesterId), 
      fetchQuestionList(this.examId, this.semesterId)
    ]);
        // 处理试题列表
    const questionList = qsListRes.data.data;
    
    // 获取所有试题详情
    const detailPromises = questionList.map(qs => 
      fetchQuestionDetail(this.examId, this.semesterId, qs.qs_id, qs.qs_type)
    );
    const detailResults = await Promise.all(detailPromises);
    this.questionData = questionList.map((qs, index) => {
      const detail = detailResults[index].data.data;
      return {
        id: qs.qs_id,
        content: qs.qs_title,
        type: this.mapQuestionType(qs.qs_type),
        accuracy: `${(qs.right_percent * 100).toFixed(1)}%`,
        scoreRate: `${(qs.score_percent * 100).toFixed(1)}%`,
        answered: qs.ans_cnt,
        unanswered: qs.un_ans_cnt,
        total: qs.total_cnt,
        knowledgePoint: detail.qsPoint?.point_content,
        correctAnswer: detail.right_ans,
        options: this.parseOptions(qs.qs_type, detail),
        answers: this.parseAnswers(qs.qs_type, detail)
      };
    });

    console.log("API 响应：", { paperRes, divisionRes, pointRes,scoreRes });

    // 修正数据绑定
    this.paperData = paperRes.data.data; // 取出 data
    this.divisionData = divisionRes.data.data;
    this.questionAverages = divisionRes.data.data.qsAvers;
    this.wordCloudData = pointRes.data.data;
    this.pieChartData = scoreRes.data.data;

    // 确保数据赋值成功
    console.log("paperData:", this.paperData);
    console.log("divisionData:", this.divisionData);
    console.log("questionAverages:", this.questionAverages);
    console.log("wordCloudData:", this.wordCloudData);
    console.log("pieChartData:", this.pieChartData);

    this.drawEChart();
    this.drawWordCloud();
    this.drawChart(); 
  } catch (error) {
    console.error("数据加载失败：", error);
  }
},

    drawEChart() {
      setTimeout(() => {
        if (!this.$refs.echart) {
          console.warn("ECharts 容器未找到，无法绘制");
          return;
        }

        console.log("绘制柱状折线图数据:", this.divisionData);
        
        const chart = echarts.init(this.$refs.echart);
        
        if (!this.divisionData.divisionDatas || !this.divisionData.divisionDatas.length) {
          console.warn("分班数据为空，无法绘制");
          return;
        }

        // 获取所有题号，保证各分班的数据对齐
        const xAxisData = this.questionAverages.map((_, index) => `第${index + 1}小题`);

        // 分班数据处理
        const series = this.divisionData.divisionDatas.map((division) => {
        const rightCounts = xAxisData.map((_, index) => {
          return division.qsDataList[index]?.right_cnt || 0;
        });
          return {
          name: `${division.division_name} 正确人数`,
          type: "bar",
          data: rightCounts,
          // 添加动画和圆角
          animationDuration: 1200,
          animationEasing: 'elasticOut',
          itemStyle: {
            borderRadius: [6, 6, 0, 0], // 顶部圆角
          }
        };
      });


        // 平均分折线
        const avgScores = xAxisData.map((_, idx) => this.questionAverages[idx] || 0);
          series.push({
            name: '平均分',
            type: "line",
            yAxisIndex: 1,
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              width: 3,
              color: '#5BB1EF'
            },
            itemStyle: {
              color: '#5BB1EF'
            },
            data: avgScores
          });

        chart.setOption({
           grid: {
          left: 60,
          right: 60,
          containLabel: true
        },
          tooltip: { trigger: "axis" },
          legend: { data: series.map(s => s.name) },
          xAxis: {
            type: "category",
            data: xAxisData,
            axisLabel: {
              interval: 0, // 强制显示所有标签
              rotate: 45  // 标签旋转防止重叠
            },
            splitLine: { show: false } // 移除垂直网格线
          },
          yAxis: [
            { 
              type: "value", 
              name: "正确人数",
              splitLine: { show: false } // 移除水平网格线
            },
            { type: "value", name: "平均分", position: "right" }
          ],
          series
        });
         window.addEventListener('resize', () => chart.resize());
         chart.resize();
      }, 100);
    },


     drawWordCloud() {
    setTimeout(() => {
      if (!this.$refs.wordCloudChart) {
        console.warn("ECharts 词云容器未找到");
        return;
      }

      const chart = echarts.init(this.$refs.wordCloudChart);
      const data = this.wordCloudData.map(item => ({
        name: item.point_content,
        value: item.point_cnt
      }));

      chart.setOption({
        tooltip: {},
          series: [{
          type: 'wordCloud',
          shape: 'cardioid',  // 改为椭圆形状
          rotationRange: [0,40],//字体旋转的角度
          sizeRange: [18, 40], // 修改字号范围
          gridSize: 4,  // 增大网格尺寸
          rotationStep: 45,
          drawOutOfBound: false,
          layoutAnimation: true,  // 开启布局动画
          textStyle: {
            color: function () {
              // 使用暖色调色系
               const hue = Math.floor(Math.random() * 360);
                return `hsl(${hue}, 90%, 80%)`; // 使用HSL更鲜艳的颜色
            },
            textBorderColor: 'rgba(0,0,0,0.2)',  // 添加文字描边
            textBorderWidth: 1
          },
          emphasis: {
            focus: 'self',
            hoverAnimation: {
              duration: 600,
              scale: 1.3,
              easing: 'elasticOut'
            }
          },
          data: data,
          // 添加渐现动画
          animationDuration: 2000,
          animationEasing: 'backInOut',
          animationDurationUpdate: 1200
        }]
      });
    }, 100);
  },

    drawPieChart() {
       const chart = echarts.init(this.$refs.pieChart);
       // 清空旧图表
      chart.clear(); 
      chart.setOption({
        tooltip: { trigger: "item" },
        legend: { bottom: 0 },
        series: [{
          name: "成绩分布",
          type: "pie",
          radius: "50%",
          data: this.pieChartData.map(item => ({
            name: item.name.replace(/_/g, ' '), // 格式化名称
            value: item.value
          }))
        }]
      });
    },
    drawFunnelChart() {
  const chart = echarts.init(this.$refs.pieChart);
  chart.clear();
  
  chart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c}人 ({d}%)'
    },
    legend: {
      bottom: 0,
      data: this.pieChartData.map(item => item.name.replace(/_/g, ' '))
    },
    series: [{
      name: '成绩分布',
      type: 'funnel',
      left: '10%',
      top: 60,
      bottom: 60,
      width: '80%',
      min: 0,
      max: Math.max(...this.pieChartData.map(item => item.value)),
      minSize: '0%',
      maxSize: '100%',
      sort: 'descending',
      gap: 2,
      label: {
        show: true,
        position: 'inside',
        formatter: '{b}: {c}人'
      },
      itemStyle: {
        borderColor: '#fff',
        borderWidth: 2
      },
      data: this.pieChartData
        .sort((a, b) => b.value - a.value)
        .map(item => ({
          name: item.name.replace(/_/g, ' '),
          value: item.value
        }))
    }]
  });
},
  }
};
</script>

<style scoped>
.combined-section .chart-row {
  display: flex;
  gap: 20px;
  margin-top: 15px;
}

.combined-section .chart-container {
  padding: 15px;
  background: #fff;
  border-radius: 8px;
}

.word-cloud {
  flex: 6;
  margin-right: 0;
}

.pie-chart {
  flex: 4;
}

.sub-title {
  font-size: 16px;
  color: #666;
  margin-bottom: 15px;
  text-align: center;
}

.section-header {
  cursor: pointer;
  position: relative;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  transition: background 0.3s;
}

.section-header:hover {
  background: #e9ecef;
}

.arrow {
  display: inline-block;
  margin-left: 10px;
  border: solid #666;
  border-width: 0 2px 2px 0;
  padding: 3px;
  transform: rotate(45deg);
  transition: transform 0.3s;
}

.arrow.rotate {
  transform: rotate(-135deg);
}

.section-title{
    font-weight: 600;
    margin-bottom: 1rem;
    color: #333;
}

.slide-enter-active, .slide-leave-active {
  transition: all 0.3s ease;
  max-height: 2000px;
  overflow: hidden;
}

.slide-enter, .slide-leave-to {
  opacity: 0;
  max-height: 0;
}
.content-section {
  background-color: #ffffff;
  padding: 20px 30px 0px;
  border-radius: 8px;
}

.analysis-section {
  padding: 15px;
}
/* 成绩概览表格 */
.score-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

.score-table th, .score-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center;
}

.score-table th {
  background-color: #f4f4f4;
}

/* 图表容器 */
.chart {
  width: 100% !important;  /* 强制图表占满容器 */
  height: 400px;           /* 适当增加高度 */
  transition: all 0.3s; /* 添加容器过渡效果 */
}

.chart-row {
  display: flex;
  justify-content: space-between;
  gap: 20px; /* 添加间距 */
  overflow: hidden; /* 防止溢出 */
}
.chart-container {
  flex: 1;
  min-width: 0; /* 允许内容收缩 */
  padding: 10px;
  background: #fff;
  border-radius: 8px;
}

.word-cloud {
  flex: 2;
  margin-right: 20px; /* 增加间距 */
}

.pie-chart {
  flex: 1;
  min-width: 400px; /* 设置最小宽度 */
}


/* 标题优化 */
.section-title {
  font-weight: bold;
  font-size: 18px;
  color: #333;
  border-left: 4px solid #007bff;
  padding-left: 12px;
  margin-bottom: 15px;
}

/* 表格美化 */
.score-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  margin-top: 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.score-table th, .score-table td {
  padding: 10px;
  text-align: center;
}

.score-table th {
  background-color: #5470C6;
  color: white;
  font-weight: bold;
}

.score-table tbody tr:nth-child(even) {
  background-color: #f9f9f9;
}

/* 鼠标悬停时行高亮 */
.score-table tbody td:hover {
  background-color: #f1f1f1;
  transition: background-color 0.3s ease-in-out;
}
.sub-title {
  font-size: 16px;
  color: #007bff; /* 改为蓝色 */
  margin: 0 0 15px 0; /* 调整下边距 */
  text-align: left; /* 左对齐 */
  padding-left: 8px;
  border-left: 4px solid #007bff; /* 添加蓝色左侧装饰线 */
  font-weight: 600;
}
.chart-container.word-cloud {
  position: relative;
  overflow: visible;
}

.circle-ripple {
  background-color: #1d1414;
  width: 60%;  /* 缩小尺寸 */
  height: 350px;
  border-radius: 50%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation: ripple 1.2s ease-out infinite;
  opacity: 0.6;
}

@keyframes ripple {
  0% {
    transform: translate(-50%, -50%) scale(0.8);
    opacity: 0.4;
  }
  100% {
    transform: translate(-50%, -50%) scale(1.4);
    opacity: 0;
  }
}
.detail-card {
  display: flex;
  gap: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  margin: 10px 0;
}

.detail-left {
  flex: 6;
  padding: 0px 40px;
  border-right: 1px solid #eee;
}

.detail-right {
  flex: 4;
  padding: 0px 20px;
}

.sub-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
  font-weight: 500;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  padding: 5px 0;
  border-bottom: 1px solid #eee;
  
}
li :last-child {
    border-bottom: none;
  }

  .correct-answer {
  color: #67C23A !important;
  font-weight: 500;
}

/* 确保原有样式没有冲突 */
.detail-left li {
  color: #606266; /* 默认颜色 */
}
.answer-tip{
    display: flex;
    justify-content: flex-start;
    gap: 60px;
    padding: 20px 0px;
}
.answer-tip span{
  font-weight: bold;
}
</style>
